import { Component, OnInit, Input } from '@angular/core';
// 导入表单相关：表单验证、表单构建、表单组
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { CveService } from 'src/app/core/service/cve.service';


// 仪表盘
const ECHRTS_V2_OPTION = {
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      name: 'scoreV2',
      type: 'gauge',
      center: ['20%', '50%'],    // 默认全局居中
      radius: '80%',
      min: 0,
      max: 10,
      axisLine: {            // 坐标轴线
        lineStyle: {       // 属性lineStyle控制线条样式
          width: 4
        }
      },
      axisTick: {            // 坐标轴小标记
        length: 12,        // 属性length控制线长
        lineStyle: {       // 属性lineStyle控制线条样式
          color: 'auto'
        }
      },
      splitLine: {           // 分隔线
        length: 20,         // 属性length控制线长
        lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
          color: 'auto'
        }
      },
      pointer: {
        width: 5,
        length: '50%'
      },
      detail: {
        formatter: '{value}', // 数值
        fontWeight: 'bolder',
        fontSize: 14,
        offsetCenter: [0, '70%']
      },
      title: {
        offsetCenter: [0, 80],
        textStyle: {       // 仪表盘中间标题
          fontWeight: 'bolder',
          fontSize: 14,
          color: '#fff'
        }
      },
      data: [
        { value: 0, name: 'BASE SCORE' }
      ]
    },
    {
      name: 'impactScoreV2',
      type: 'gauge',
      center: ['50%', '50%'],    // 默认全局居中
      radius: '80%',
      min: 0,
      max: 10,
      axisLine: {            // 坐标轴线
        lineStyle: {       // 属性lineStyle控制线条样式
          width: 4
        }
      },
      axisTick: {            // 坐标轴小标记
        length: 12,        // 属性length控制线长
        lineStyle: {       // 属性lineStyle控制线条样式
          color: 'auto'
        }
      },
      splitLine: {           // 分隔线
        length: 20,         // 属性length控制线长
        lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
          color: 'auto'
        }
      },
      pointer: {
        width: 5,
        length: '50%'
      },
      detail: {
        formatter: '{value}',
        // 其余属性默认使用全局文本样式，详见TEXTSTYLE
        fontWeight: 'bolder',
        fontSize: 14,
        offsetCenter: [0, '70%']
      },
      title: {
        offsetCenter: [0, 80],
        textStyle: {       // 仪表盘中间标题
          fontWeight: 'bolder',
          fontSize: 14,
          color: '#fff'
        }
      },
      data: [
        { value: 0, name: 'IMPACT' }
      ]
    },
    {
      name: 'exploitabilityScoreV2',
      type: 'gauge',
      center: ['80%', '50%'],    // 默认全局居中
      radius: '80%',
      min: 0,
      max: 10,
      axisLine: {            // 坐标轴线
        lineStyle: {       // 属性lineStyle控制线条样式
          width: 4
        }
      },
      axisTick: {            // 坐标轴小标记
        length: 12,        // 属性length控制线长
        lineStyle: {       // 属性lineStyle控制线条样式
          color: 'auto'
        }
      },
      splitLine: {           // 分隔线
        length: 20,         // 属性length控制线长
        lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
          color: 'auto'
        }
      },
      pointer: {
        width: 5,
        length: '50%'
      },
      detail: {
        formatter: '{value}',
        // 其余属性默认使用全局文本样式，详见TEXTSTYLE
        fontWeight: 'bolder',
        fontSize: 14,
        offsetCenter: [0, '70%']
      },
      title: {
        offsetCenter: [0, 80],
        textStyle: {       // 仪表盘中间标题
          fontWeight: 'bolder',
          fontSize: 14,
          color: '#fff'
        }
      },
      data: [{ value: 0, name: 'EXPLOITABILITY' }]
    },
  ]
};
const ECHRTS_V3_OPTION = {
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      name: 'scoreV3',
      type: 'gauge',
      center: ['20%', '50%'],    // 默认全局居中
      radius: '80%',
      min: 0,
      max: 10,
      axisLine: {            // 坐标轴线
        lineStyle: {       // 属性lineStyle控制线条样式
          width: 4
        }
      },
      axisTick: {            // 坐标轴小标记
        length: 12,        // 属性length控制线长
        lineStyle: {       // 属性lineStyle控制线条样式
          color: 'auto'
        }
      },
      splitLine: {           // 分隔线
        length: 20,         // 属性length控制线长
        lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
          color: 'auto'
        }
      },
      pointer: {
        width: 5,
        length: '50%'
      },
      detail: {
        formatter: '{value}',
        // 其余属性默认使用全局文本样式，详见TEXTSTYLE
        fontWeight: 'bolder',
        fontSize: 14,
        offsetCenter: [0, '70%']
      },
      title: {
        offsetCenter: [0, 80],
        textStyle: {       // 仪表盘中间标题
          fontWeight: 'bolder',
          fontSize: 14,
          color: '#fff'
        }
      },
      data: [
        { value: 0, name: 'BASE SCORE' }
      ]
    },
    {
      name: 'impactScoreV3',
      type: 'gauge',
      center: ['50%', '50%'],    // 默认全局居中
      radius: '80%',
      min: 0,
      max: 10,
      axisLine: {            // 坐标轴线
        lineStyle: {       // 属性lineStyle控制线条样式
          width: 4
        }
      },
      axisTick: {            // 坐标轴小标记
        length: 12,        // 属性length控制线长
        lineStyle: {       // 属性lineStyle控制线条样式
          color: 'auto'
        }
      },
      splitLine: {           // 分隔线
        length: 20,         // 属性length控制线长
        lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
          color: 'auto'
        }
      },
      pointer: {
        width: 5,
        length: '50%'
      },
      detail: {
        formatter: '{value}',
        // 其余属性默认使用全局文本样式，详见TEXTSTYLE
        fontWeight: 'bolder',
        fontSize: 14,
        offsetCenter: [0, '70%']
      },
      title: {
        offsetCenter: [0, 80],
        textStyle: {       // 仪表盘中间标题
          fontWeight: 'bolder',
          fontSize: 14,
          color: '#fff'
        }
      },
      data: [
        { value: 0, name: 'IMPACT' }
      ]
    },
    {
      name: 'exploitabilityScoreV3',
      type: 'gauge',
      center: ['80%', '50%'],    // 默认全局居中
      radius: '80%',
      min: 0,
      max: 10,
      axisLine: {            // 坐标轴线
        lineStyle: {       // 属性lineStyle控制线条样式
          width: 4
        }
      },
      axisTick: {            // 坐标轴小标记
        length: 12,        // 属性length控制线长
        lineStyle: {       // 属性lineStyle控制线条样式
          color: 'auto'
        }
      },
      splitLine: {           // 分隔线
        length: 20,         // 属性length控制线长
        lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
          color: 'auto'
        }
      },
      pointer: {
        width: 5,
        length: '50%'
      },
      detail: {
        formatter: '{value}',
        // 其余属性默认使用全局文本样式，详见TEXTSTYLE
        fontWeight: 'bolder',
        fontSize: 14,
        offsetCenter: [0, '70%']
      },
      title: {
        offsetCenter: [0, 80],
        textStyle: {       // 仪表盘中间标题
          fontWeight: 'bolder',
          fontSize: 14,
          color: '#fff'
        }
      },
      data: [{ value: 0, name: 'EXPLOITABILITY' }]
    },
  ]
};
@Component({
  selector: 'app-cve-modal',
  templateUrl: './cve-modal.component.html',
  styleUrls: ['./cve-modal.component.scss']
})
export class CveModalComponent implements OnInit {
  @Input() title: string;
  @Input() subtitle: string;
  defaultValue = 'CVE';
  info = {};
  type = '';
  isCve = true;
  // === old ===
  // cveandcnnvdForm: FormGroup;
  // cveForm: FormGroup;
  // cnnvdForm: FormGroup;

  // === new ===
  cvssV2WatchList = []; // 监控v2单选
  cvssV3WatchList = []; // 监控v3单选
  cveForm: FormGroup;
  cveRefDataSwitch = false; // 显示cveRefData
  cveRefData = []; // 存储多个ref数据
  cveRefDataOne = []; // 存储单个ref数据
  cveRefCount = 0; // 计数refer 表单数量
  refList = []; // 用于reference多个表单数据显示
  // cvssV2 选项组
  accessVectorV2 = '';
  accessComplexityV2 = '';
  authenticationV2 = '';
  confidentialityImpactV2 = '';
  integrityImpactV2 = '';
  availabilityImpactV2 = '';
  // cvssV3 选项组
  attackVectorV3 = '';
  attackComplexityV3 = '';
  privilegesRequiredV3 = '';
  userInteractionV3 = '';
  scopeV3 = '';
  confidentialityImpactV3 = '';
  integrityImpactV3 = '';
  availabilityImpactV3 = '';
  //  仪表盘
  optionV2 = ECHRTS_V2_OPTION;
  optionV3 = ECHRTS_V3_OPTION;
  constructor(
    private modal: NzModalRef,
    private message: NzMessageService,
    private cveService: CveService,
    fb: FormBuilder
  ) {
    // === old ===
    // this.cveForm = fb.group({
    //   type: ['CVE', Validators.required],
    //   cveName: ['', Validators.required],
    //   score: ['', Validators.required],
    //   availabilityImpact: ['NONE'],
    //   accessVector: ['NETWORK'],
    //   accessComplexity: ['LOW'],
    //   confidentialityImpact: ['NONE'],
    //   integrityImpact: ['NONE'],
    //   description: [''],
    //   cwe: [''],
    // });
    // this.cnnvdForm = fb.group({
    //   type: ['CNNVD', Validators.required],
    //   cnnvdName: ['', Validators.required],
    //   cnnvdId: ['', Validators.required],
    //   publishedDate: ['', Validators.required],
    //   source: [''],
    //   severity: ['低危', Validators.required],
    //   vulnType: ['', Validators.required],
    //   thrtype: ['', Validators.required],
    //   vulnDescript: [''],
    //   cveId: ['', Validators.required],
    //   vulnSolution: ['']
    // });

    // this.cveandcnnvdForm = this.cveForm;
    // this.cveForm.controls.type.valueChanges.subscribe((value) => {
    //   this.changeCveOrCnnve(value);
    // });
    // this.cnnvdForm.controls.type.valueChanges.subscribe((value) => {
    //   this.changeCveOrCnnve(value);
    // });

    // === new ===
    this.cveForm = fb.group({
      name: ['', Validators.required], // CVE编号
      publishedDate: ['', Validators.required], // 发布时间
      lastModifiedDate: ['', Validators.required], // 最近修改时间
      description: ['', Validators.required], // 描述
      referenceUrl: ['', Validators.required], // 引用地址
      referenceName: ['', Validators.required], // 引用名称
      referenceSource: ['', Validators.required], // 引用源
      referenceTags: ['', Validators.required], // 引用标签
      accessVectorV2: [''], // 访问类型
      accessComplexityV2: [''], // 访问复杂性
      authenticationV2: [''], // 身份认证
      confidentialityImpactV2: [''], // 保密性影响
      integrityImpactV2: [''], // 完整性影响
      availabilityImpactV2: [''], // 可用性影响
      attackVectorV3: [''], // 访问类型
      attackComplexityV3: [''], // 访问复杂性
      privilegesRequiredV3: [''], // 权限要求
      userInteractionV3: [''], // 用户交互
      scopeV3: [''], // 范围
      confidentialityImpactV3: [''], // 保密性影响
      integrityImpactV3: [''], // 完整性影响
      availabilityImpactV3: [''] // 可用性影响
    });
  }
  // ======================// old //=============================
  // addCEVAndCNNVD(): void {
  //   console.log(this.cveandcnnvdForm.controls);
  //   // tslint:disable-next-line:forin
  //   for (const c in this.cveandcnnvdForm.controls) {
  //     this.cveandcnnvdForm.controls[c].markAsTouched();
  //   }
  //   if (this.cveandcnnvdForm.valid) {
  //     if (this.cveandcnnvdForm.controls.type.value === 'CVE') {
  //       this.info = {
  //         'name': this.cveandcnnvdForm.value.cveName,
  //         'score': this.cveandcnnvdForm.value.score,
  //         'availability_impact': this.cveandcnnvdForm.value.availabilityImpact,
  //         'access_vector': this.cveandcnnvdForm.value.accessVector,
  //         'access_complexity': this.cveandcnnvdForm.value.accessComplexity,
  //         'confidentiality_impact': this.cveandcnnvdForm.value.confidentialityImpact,
  //         'integrity_impact': this.cveandcnnvdForm.value.integrityImpact,
  //         'description': this.cveandcnnvdForm.value.description,
  //         'cwe': this.cveandcnnvdForm.value.cwe
  //       };
  //       this.type = 'CVE';
  //     }
  //     if (this.cveandcnnvdForm.controls.type.value === 'CNNVD') {
  //       console.log('=== type ===', this.cveandcnnvdForm.value.type);
  //       this.info = {
  //         'name': this.cveandcnnvdForm.value.cnnvdName,
  //         'cnnvd_id': this.cveandcnnvdForm.value.cnnvdId,
  //         'published_date': this.cveandcnnvdForm.value.publishedDate,
  //         'modified_date': '',
  //         'source': this.cveandcnnvdForm.value.source,
  //         'severity': this.cveandcnnvdForm.value.severity,
  //         'vuln_type': this.cveandcnnvdForm.value.vulnType,
  //         'thrtype': this.cveandcnnvdForm.value.thrtype,
  //         'vuln_descript': this.cveandcnnvdForm.value.vulnDescript,
  //         'cve_id': this.cveandcnnvdForm.value.cveId,
  //         'bugtraq_id': '',
  //         'vuln_solution': this.cveandcnnvdForm.value.vulnSolution
  //       };
  //       this.type = 'CNNVD';
  //     }

  //     console.log(' form-group===this.type===> ', this.type);
  //     this.addService(JSON.stringify(this.info), this.type);
  //   } else {
  //     this.message.error('表单校验失败', { nzDuration: 8000 });
  //   }
  // }
  // ================// new //=========================
  addCveInfo() {
    console.log("=== cveFormInfo ===", this.cveForm);
    if (this.cveForm.valid) {
      if (!this.cveRefDataSwitch && this.cveRefCount === 0) { // 单个
        let refObj = {
          url: this.cveForm.value.referenceUrl,
          name: this.cveForm.value.referenceName,
          refsource: this.cveForm.value.referenceSource,
          tags: this.cveForm.value.referenceTags
        };
        this.cveRefDataOne.push(refObj);
      }
      let postData = {
        'type': 'cve',
        'cpeInfo': '',
        'cnnvdInfo': '',
        'tCveReferenceVo': {
          name: this.cveForm.value.name,
          publishedDate: this.cveForm.value.publishedDate ? ((this.cveForm.value.publishedDate).getTime()).toString() : '',
          lastModifiedDate: this.cveForm.value.lastModifiedDate ? ((this.cveForm.value.lastModifiedDate).getTime()).toString() : '',
          description: this.cveForm.value.description,
          tCveReferenceList: (this.cveRefDataSwitch && this.cveRefCount > 0) ? this.cveRefData : this.cveRefDataOne,
          accessVectorV2: this.cveForm.value.accessVectorV2,
          accessComplexityV2: this.cveForm.value.accessComplexityV2,
          authenticationV2: this.cveForm.value.authenticationV2, // 身份认证
          confidentialityImpactV2: this.cveForm.value.confidentialityImpactV2, // 保密性影响
          integrityImpactV2: this.cveForm.value.integrityImpactV2, // 完整性影响
          availabilityImpactV2: this.cveForm.value.availabilityImpactV2, // 可用性影响
          attackVectorV3: this.cveForm.value.attackVectorV3, // 访问类型
          attackComplexityV3: this.cveForm.value.attackComplexityV3, // 访问复杂性
          privilegesRequiredV3: this.cveForm.value.privilegesRequiredV3, // 权限要求
          userInteractionV3: this.cveForm.value.userInteractionV3, // 用户交互
          scopeV3: this.cveForm.value.scopeV3, // 范围
          confidentialityImpactV3: this.cveForm.value.confidentialityImpactV3, // 保密性影响
          integrityImpactV3: this.cveForm.value.integrityImpactV3, // 完整性影响
          availabilityImpactV3: this.cveForm.value.availabilityImpactV3 // 可用性影响
        }
      };
      console.log('=== postData ===', postData);
      // this.addService(postData);
    }
     // else {
      //   this.message.error('表单校验失败', { nzDuration: 10000 });
      // }
  }
    addCveList() {
      this.cveRefDataSwitch = true;
      this.cveRefCount++;
      this.getRefList();
      this.getRefData();
    }
    onLoadMore(array) { // 多ref 视图更新
      this.refList = [...array];
      console.log('== more ==', this.refList);
    }
  private getRefList() { // 多ref数据显示
    let obj = {
      title: ('data' + this.cveRefCount),
      url: this.cveForm.value.referenceUrl,
      name: this.cveForm.value.referenceName,
      refsource: this.cveForm.value.referenceSource,
      tags: this.cveForm.value.referenceTags
    };
    this.refList.push(obj);
    console.log('=== refList ===', this.refList);
    this.onLoadMore(this.refList);
  }
  private getRefData() { // 多ref数据处理
    let obj = {
      referenceUrl: this.cveForm.value.referenceUrl,
      referenceName: this.cveForm.value.referenceName,
      referenceSource: this.cveForm.value.referenceSource,
      referenceTags: this.cveForm.value.referenceTags
    };
    this.cveRefData.push(obj);
    this.cveForm.patchValue({
      referenceUrl: '',
      referenceName: '',
      referenceSource: '',
      referenceTags: '',
    });
  }
  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }
  cvssV2Watcher(event) {
    if (this.accessVectorV2 && this.accessComplexityV2 &&
      this.authenticationV2 && this.confidentialityImpactV2
      && this.integrityImpactV2 && this.availabilityImpactV2) {
      let postData = {
        integrityImpactV2: this.integrityImpactV2,
        accessComplexityV2: this.accessComplexityV2,
        accessVectorV2: this.accessVectorV2,
        authenticationV2: this.authenticationV2,
        availabilityImpactV2: this.availabilityImpactV2,
        confidentialityImpactV2: this.confidentialityImpactV2
      };
      console.log('== this.getV2Score == ', postData);
      // 仪表盘数据更新处理
      this.cveService.getV2Score(postData).subscribe(
        (params) => {
          console.log('== this.getV2Score Result == ', params);
          this.optionV2.series[0].data[0].value = parseFloat(params.data.scoreV2);
          this.optionV2.series[1].data[0].value = parseFloat(params.data.exploitabilityScoreV2);
          this.optionV2.series[2].data[0].value = parseFloat(params.data.impactScoreV2);
          this.optionV2 = Object.assign({}, this.optionV2);
        }
      );
    }
  }
  cvssV3Watcher(event) {
    if (this.attackComplexityV3 && this.attackVectorV3 &&
      this.availabilityImpactV3 && this.confidentialityImpactV3
      && this.privilegesRequiredV3 && this.integrityImpactV3 &&
      this.userInteractionV3 && this.scopeV3) {
      let postData = {
        attackComplexityV3: this.attackComplexityV3,
        attackVectorV3: this.attackVectorV3,
        availabilityImpactV3: this.availabilityImpactV3,
        confidentialityImpactV3: this.confidentialityImpactV3,
        privilegesRequiredV3: this.privilegesRequiredV3,
        integrityImpactV3: this.integrityImpactV3,
        userInteractionV3: this.userInteractionV3,
        scopeV3: this.scopeV3
      };
      console.log('== this.getV3Score == ', postData);
      // 仪表盘数据更新处理
      this.cveService.getV3Score(postData).subscribe(
        (params) => {
          console.log('== this.getV2Score Result == ', params);
          this.optionV3.series[0].data[0].value = parseFloat(params.data.scoreV3);
          this.optionV3.series[1].data[0].value = parseFloat(params.data.exploitabilityScoreV3);
          this.optionV3.series[2].data[0].value = parseFloat(params.data.impactScoreV3);
          this.optionV3 = Object.assign({}, this.optionV3);
        }
      );
    }
  }
  ngOnInit() {
  }
  // ======================// old //=============================
  // private addService(info: string, type: string) {
  //   this.cveService.addCVEAndCNNVD(info, type).subscribe((addResult) => {
  //     // this.result = result;   // 返回的结果
  //     console.log('==result==', addResult);
  //     if (addResult.status) {
  //       this.message.success('添加成功!', {
  //         nzDuration: 10000
  //       });
  //       this.modal.destroy({ data: 'this the result data' });
  //     } else {
  //       this.message.error('添加失败!请检查后重新填写', {
  //         nzDuration: 10000
  //       });
  //     }
  //   });
  // }

  // private changeCveOrCnnve(value) {
  //   console.log(value, this.cveandcnnvdForm.controls.type.value);
  //   if (value === 'CVE') {
  //     this.cveandcnnvdForm = this.cveForm;
  //     this.isCve = true;
  //   }

  //   if (value === 'CNNVD') {
  //     this.cveandcnnvdForm = this.cnnvdForm;
  //     this.isCve = false;
  //   }
  // }
  // ======================// new //=============================
  private addService(data) {
    this.cveService.addCveAndCnnvdInfo(data).subscribe(params => {
      console.log('result', params);
      if (params.status) {
        this.message.success('添加成功!', {
          nzDuration: 10000
        });
        this.cveRefCount = 0;
        this.cveRefDataSwitch = false;
        this.modal.destroy({ data: 'this the result data' });
      } else {
        this.cveRefCount = 0;
        this.cveRefDataSwitch = false;
        this.message.error('添加失败!请检查后重新填写', {
          nzDuration: 10000
        });
      }
    });
  }


}
